!function () {
  let model = Model({ resourceName: "message" });

  let view = View("section.message");

  let controller = Controller({
    messageList: null,
    form: null,
    init: function (view, controller) {
      this.messageList = view.querySelector("#messageList");
      this.form = view.querySelector("#postMessageForm");
      this.loadMessages();
    },
    loadMessages: function () {
      this.model.fetch().then((messages) => {
        let array = messages.map((item) => {
          return item.attributes;
        });
        array.forEach((item) => {
          let li = document.createElement("li");
          li.innerText = `${item.name}: ${item.content}`;
          this.messageList.appendChild(li);
        });
      });
    },
    bindEvents: function () {
      this.form.addEventListener("submit", (e) => {
        e.preventDefault();
        this.saveMessage();
      });
    },
    saveMessage: function () {
      let myForm = this.form;
      let name = myForm.querySelector("input[name=name]").value;
      let content = myForm.querySelector("input[name=content]").value;
      if (name === "" && content === "") {
        alert("你是谁？想说啥？");
      } else if (name === "") {
        alert("你是谁？");
      } else if (content === "") {
        alert("想说啥？");
      } else {
        this.model.save({ name: name, content: content }).then(
          (object) => {
            let li = document.createElement("li");
            li.innerText = `${object.attributes.name}: ${object.attributes.content}`;
            this.messageList.appendChild(li);
            myForm.querySelector("input[name=content]").value = "";
          },
          (error) => console.log(error)
        );
      }
    },
  });

  controller.init(view, model);
}.call();
